<template>
  <div class="realtime-waveform">
    <div class="waveform-header">
      <div class="title-section">
        <h3>实时加速度波形图</h3>
        <div class="device-info">
          <span>设备ID: {{ deviceId }}</span>
          <span class="separator">|</span>
          <span>传感器: {{ sensorId || '全部' }}</span>
        </div>
      </div>

      <div class="control-section">
        <el-button-group size="small">
          <el-button
            :type="isRealtime ? 'primary' : 'default'"
            @click="toggleRealtime"
            :icon="isRealtime ? 'el-icon-video-pause' : 'el-icon-video-play'"
          >
            {{ isRealtime ? '暂停' : '开始' }}
          </el-button>
          <el-button @click="clearChart" icon="el-icon-delete">清空</el-button>
          <el-button @click="resetZoom" icon="el-icon-refresh-left">重置缩放</el-button>
        </el-button-group>

        <el-dropdown @command="handleWindowSizeChange" style="margin-left: 10px;">
          <el-button size="small">
            窗口: {{ windowSize }}s <i class="el-icon-arrow-down el-icon--right"></i>
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="30">30秒</el-dropdown-item>
            <el-dropdown-item command="60">1分钟</el-dropdown-item>
            <el-dropdown-item command="120">2分钟</el-dropdown-item>
            <el-dropdown-item command="300">5分钟</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
    </div>

    <div class="waveform-content">
      <div class="chart-container" ref="chartContainer"></div>

      <div class="status-bar">
        <div class="data-info">
          <span>数据点数: {{ totalDataPoints }}</span>
          <span class="separator">|</span>
          <span>更新频率: {{ updateFrequency }}Hz</span>
          <span class="separator">|</span>
          <span>延迟: {{ latency }}ms</span>
        </div>

        <div class="connection-status">
          <websocket-status :show-online-count="false" />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { mapGetters } from 'vuex'
import WebSocketStatus from '@/components/WebSocketStatus'

export default {
  name: 'RealtimeWaveform',
  components: {
    WebSocketStatus
  },
  props: {
    deviceId: {
      type: String,
      required: true
    },
    sensorId: {
      type: String,
      default: null
    },
    // 滑动窗口大小（秒）
    windowSize: {
      type: Number,
      default: 60
    },
    // 最大数据点数
    maxDataPoints: {
      type: Number,
      default: 1000
    }
  },
  data() {
    return {
      chart: null,
      isRealtime: false,

      // 数据存储
      timeData: [], // 时间轴数据
      xAxisData: [], // X轴加速度数据
      yAxisData: [], // Y轴加速度数据
      zAxisData: [], // Z轴加速度数据

      // 统计信息
      totalDataPoints: 0,
      updateFrequency: 0,
      latency: 0,

      // 性能监控
      lastUpdateTime: 0,
      updateCount: 0,
      frequencyTimer: null,

      // 图表配置
      chartOption: null
    }
  },
  computed: {
    ...mapGetters('websocket', ['connectionInfo']),

    isConnected() {
      return this.connectionInfo.isConnected
    }
  },
  mounted() {
    this.initChart()
    this.setupWebSocketListeners()
    this.startFrequencyMonitor()
  },
  beforeDestroy() {
    this.cleanup()
  },
  methods: {
    /**
     * 初始化图表
     */
    initChart() {
      if (this.chart) {
        this.chart.dispose()
      }

      this.chart = echarts.init(this.$refs.chartContainer)

      this.chartOption = {
        title: {
          text: '实时加速度波形',
          left: 'center',
          textStyle: {
            fontSize: 16,
            fontWeight: 'bold'
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          },
          formatter: (params) => {
            if (!params || params.length === 0) return ''

            const time = params[0].axisValue
            let content = `时间: ${time}<br/>`

            params.forEach(param => {
              content += `${param.seriesName}: ${param.value.toFixed(4)} m/s²<br/>`
            })

            return content
          }
        },
        legend: {
          data: ['X轴', 'Y轴', 'Z轴'],
          top: 30
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '10%',
          top: '15%',
          containLabel: true
        },
        toolbox: {
          feature: {
            dataZoom: {
              yAxisIndex: 'none'
            },
            restore: {},
            saveAsImage: {}
          }
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: this.timeData,
          axisLabel: {
            formatter: (value) => {
              const date = new Date(value)
              return date.toLocaleTimeString()
            }
          }
        },
        yAxis: {
          type: 'value',
          name: '加速度 (m/s²)',
          axisLabel: {
            formatter: '{value}'
          }
        },
        dataZoom: [
          {
            type: 'inside',
            start: 70,
            end: 100
          },
          {
            start: 70,
            end: 100,
            handleIcon: 'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23.1h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
            handleSize: '80%',
            handleStyle: {
              color: '#fff',
              shadowBlur: 3,
              shadowColor: 'rgba(0, 0, 0, 0.6)',
              shadowOffsetX: 2,
              shadowOffsetY: 2
            }
          }
        ],
        series: [
          {
            name: 'X轴',
            type: 'line',
            data: this.xAxisData,
            smooth: true,
            symbol: 'none',
            lineStyle: {
              color: '#ff6b6b',
              width: 2
            },
            areaStyle: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [
                  { offset: 0, color: 'rgba(255, 107, 107, 0.3)' },
                  { offset: 1, color: 'rgba(255, 107, 107, 0.1)' }
                ]
              }
            }
          },
          {
            name: 'Y轴',
            type: 'line',
            data: this.yAxisData,
            smooth: true,
            symbol: 'none',
            lineStyle: {
              color: '#4ecdc4',
              width: 2
            },
            areaStyle: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [
                  { offset: 0, color: 'rgba(78, 205, 196, 0.3)' },
                  { offset: 1, color: 'rgba(78, 205, 196, 0.1)' }
                ]
              }
            }
          },
          {
            name: 'Z轴',
            type: 'line',
            data: this.zAxisData,
            smooth: true,
            symbol: 'none',
            lineStyle: {
              color: '#45b7d1',
              width: 2
            },
            areaStyle: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [
                  { offset: 0, color: 'rgba(69, 183, 209, 0.3)' },
                  { offset: 1, color: 'rgba(69, 183, 209, 0.1)' }
                ]
              }
            }
          }
        ]
      }

      this.chart.setOption(this.chartOption)

      // 监听窗口大小变化
      window.addEventListener('resize', this.handleResize)
    },

    /**
     * 设置WebSocket监听器
     */
    setupWebSocketListeners() {
      // 监听设备信息更新
      this.$store.watch(
        (state) => state.websocket.deviceInfo,
        (newDeviceInfo) => {
          if (this.isRealtime) {
            this.handleRealtimeData(newDeviceInfo)
          }
        },
        { deep: true }
      )
    },

    /**
     * 处理实时数据
     */
    handleRealtimeData(deviceInfoList) {
      if (!Array.isArray(deviceInfoList)) return

      // 找到当前设备的数据
      const deviceData = deviceInfoList.find(item => item.deviceId === this.deviceId)
      if (!deviceData) return

      // 如果指定了传感器ID，进行过滤
      if (this.sensorId && deviceData.sensorId !== this.sensorId) return

      const currentTime = new Date().getTime()
      this.latency = currentTime - (deviceData.timestamp || currentTime)

      // 添加新数据点
      this.addDataPoint({
        timestamp: deviceData.timestamp || currentTime,
        xRms: deviceData.xRms || 0,
        yRms: deviceData.yRms || 0,
        zRms: deviceData.zRms || 0
      })

      this.updateChart()
    },

    /**
     * 添加数据点（滑动窗口实现）
     */
    addDataPoint(dataPoint) {
      const timestamp = new Date(dataPoint.timestamp).getTime()
      const timeStr = new Date(timestamp).toISOString()

      // 添加新数据点
      this.timeData.push(timeStr)
      this.xAxisData.push(dataPoint.xRms)
      this.yAxisData.push(dataPoint.yRms)
      this.zAxisData.push(dataPoint.zRms)

      // 实现滑动窗口：移除超出时间窗口的数据
      const windowMs = this.windowSize * 1000
      const cutoffTime = timestamp - windowMs

      while (this.timeData.length > 0) {
        const firstTime = new Date(this.timeData[0]).getTime()
        if (firstTime < cutoffTime) {
          this.timeData.shift()
          this.xAxisData.shift()
          this.yAxisData.shift()
          this.zAxisData.shift()
        } else {
          break
        }
      }

      // 限制最大数据点数
      if (this.timeData.length > this.maxDataPoints) {
        const removeCount = this.timeData.length - this.maxDataPoints
        this.timeData.splice(0, removeCount)
        this.xAxisData.splice(0, removeCount)
        this.yAxisData.splice(0, removeCount)
        this.zAxisData.splice(0, removeCount)
      }

      this.totalDataPoints = this.timeData.length
      this.updateCount++
    },

    /**
     * 更新图表
     */
    updateChart() {
      if (!this.chart || !this.isRealtime) return

      // 更新数据
      this.chart.setOption({
        xAxis: {
          data: this.timeData
        },
        series: [
          { data: this.xAxisData },
          { data: this.yAxisData },
          { data: this.zAxisData }
        ]
      }, false)

      // 自动滚动到最新数据
      if (this.timeData.length > 50) {
        const dataLength = this.timeData.length
        const start = Math.max(0, ((dataLength - 50) / dataLength) * 100)

        this.chart.setOption({
          dataZoom: [{
            start: start,
            end: 100
          }]
        }, false)
      }
    },

    /**
     * 加载历史数据
     */
    async loadHistoricalData() {
      try {
        // 获取最近的历史数据作为初始数据
        const endTime = new Date()
        const startTime = new Date(endTime.getTime() - this.windowSize * 1000)

        // 调用API获取历史数据
        let historicalData
        try {
          const { getRecentWaveformData } = await import('@/api/real/waveform')
          const response = await getRecentWaveformData(
            this.deviceId,
            this.sensorId,
            this.windowSize / 60 // 转换为分钟
          )
          historicalData = this.processApiData(response.data)
        } catch (error) {
          console.warn('获取历史数据失败，使用模拟数据:', error)
          historicalData = this.generateMockHistoricalData(startTime, endTime)
        }

        // 清空现有数据
        this.clearData()

        // 添加历史数据
        historicalData.forEach(point => {
          this.addDataPoint(point)
        })

        this.updateChart()

      } catch (error) {
        console.error('加载历史数据失败:', error)
        this.$message.error('加载历史数据失败')
      }
    },

    /**
     * 处理API返回的数据
     */
    processApiData(apiData) {
      if (!apiData || !Array.isArray(apiData)) {
        return []
      }

      return apiData.map(item => ({
        timestamp: new Date(item.timestamp).getTime(),
        xRms: item.xRms || item.x_rms || 0,
        yRms: item.yRms || item.y_rms || 0,
        zRms: item.zRms || item.z_rms || 0
      }))
    },

    /**
     * 生成模拟历史数据（用于演示）
     */
    generateMockHistoricalData(startTime, endTime) {
      const data = []
      const interval = 1000 // 1秒间隔

      for (let time = startTime.getTime(); time <= endTime.getTime(); time += interval) {
        data.push({
          timestamp: time,
          xRms: Math.random() * 2 + Math.sin(time / 10000) * 0.5,
          yRms: Math.random() * 2 + Math.cos(time / 8000) * 0.5,
          zRms: Math.random() * 2 + Math.sin(time / 12000) * 0.5
        })
      }

      return data
    },

    /**
     * 切换实时模式
     */
    async toggleRealtime() {
      if (!this.isConnected) {
        this.$message.warning('WebSocket未连接，无法启动实时模式')
        return
      }

      this.isRealtime = !this.isRealtime

      if (this.isRealtime) {
        // 启动实时模式前先加载历史数据
        await this.loadHistoricalData()
        this.$message.success('实时模式已启动')
      } else {
        this.$message.info('实时模式已暂停')
      }
    },

    /**
     * 清空图表
     */
    clearChart() {
      this.clearData()
      this.updateChart()
      this.$message.success('图表已清空')
    },

    /**
     * 清空数据
     */
    clearData() {
      this.timeData = []
      this.xAxisData = []
      this.yAxisData = []
      this.zAxisData = []
      this.totalDataPoints = 0
    },

    /**
     * 重置缩放
     */
    resetZoom() {
      if (this.chart) {
        this.chart.setOption({
          dataZoom: [{
            start: 0,
            end: 100
          }]
        })
      }
    },

    /**
     * 处理窗口大小变化
     */
    handleWindowSizeChange(size) {
      this.windowSize = parseInt(size)
      this.$message.success(`窗口大小已设置为 ${size} 秒`)

      // 重新加载数据以适应新的窗口大小
      if (this.isRealtime) {
        this.loadHistoricalData()
      }
    },

    /**
     * 处理窗口大小调整
     */
    handleResize() {
      if (this.chart) {
        this.chart.resize()
      }
    },

    /**
     * 开始频率监控
     */
    startFrequencyMonitor() {
      this.frequencyTimer = setInterval(() => {
        this.updateFrequency = this.updateCount
        this.updateCount = 0
      }, 1000)
    },

    /**
     * 清理资源
     */
    cleanup() {
      if (this.chart) {
        this.chart.dispose()
        this.chart = null
      }

      if (this.frequencyTimer) {
        clearInterval(this.frequencyTimer)
        this.frequencyTimer = null
      }

      window.removeEventListener('resize', this.handleResize)
    }
  }
}
</script>

<style lang="scss" scoped>
.realtime-waveform {
  height: 100%;
  display: flex;
  flex-direction: column;

  .waveform-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px;
    border-bottom: 1px solid #ebeef5;
    background: #fafafa;

    .title-section {
      h3 {
        margin: 0 0 4px 0;
        color: #303133;
        font-size: 18px;
      }

      .device-info {
        font-size: 12px;
        color: #909399;

        .separator {
          margin: 0 8px;
        }
      }
    }

    .control-section {
      display: flex;
      align-items: center;
    }
  }

  .waveform-content {
    flex: 1;
    display: flex;
    flex-direction: column;

    .chart-container {
      flex: 1;
      min-height: 400px;
    }

    .status-bar {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 8px 16px;
      background: #f5f7fa;
      border-top: 1px solid #ebeef5;
      font-size: 12px;

      .data-info {
        color: #606266;

        .separator {
          margin: 0 8px;
          color: #dcdfe6;
        }
      }
    }
  }
}
</style>
